package com.cms.common.controller;

import java.awt.image.BufferedImage;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.cms.kernel.util.RequestUtil;
import com.cms.kernel.util.ResponseUtil;
import com.octo.captcha.service.image.ImageCaptchaService;

/**
 * Copyright (C) 2013 2016 Well
 * 文件:CaptchaController.java
 * 创建:Well
 * 日期:2016年6月7日 上午10:03:34
 * 来自:
 * 版本:0.9.2
 * 描述:验证码的controller类
 * 		验证码的框架采用jcaptcha框架
 */

@Controller
@RequestMapping("/captcha")
public class CaptchaController
{
	@Autowired
	private ImageCaptchaService imageCaptchaService;
	
	/**
	 * 生成图片验证码，并将该图片验证码相应到前台页面
	 * 这里只实现了简单的验证码生成，可以参考jcaptcha的文档进行拓展，验证码的图片响应到index.jsp页面中
	 * @param request
	 * @param response
	 */
	@RequestMapping(value="/imageCaptcha.jpg",method={RequestMethod.GET,RequestMethod.POST})
	public void imageCaptcha(HttpServletRequest request,HttpServletResponse response)
	{
		String id=RequestUtil.getSessionID(request);
		BufferedImage bufferedImage=imageCaptchaService.getImageChallengeForID(id,request.getLocale());
		ResponseUtil.renderImageCaptcha(response, bufferedImage);
	}
	
	/**
	 * 验证输入的验证码是否正确
	 * @param request
	 * @return
	 */
	@RequestMapping(value="/validateImageCapctha",method={RequestMethod.GET,RequestMethod.POST})
	@ResponseBody
	public boolean validateImageCapctha(HttpServletRequest request)
	{
		String id=RequestUtil.getSessionID(request);
        String captcha=RequestUtil.getString(request,"captcha"); // 前台输入的验证码
        /* 
			TODO：需要改进
          	如果验证码的请求频率太快，会报如下异常：
        	Invalid ID, could not validate unexisting or already validated captcha
        */
        return imageCaptchaService.validateResponseForID(id, captcha).booleanValue(); // 判断输入的校验码是否正确
	}
	
}
